<template>
  <div class="create-course-container">
    <el-card class="course-form-card">
      <template #header>
        <div class="card-header">
          <h2>新建课程</h2>
        </div>
      </template>
      
      <el-form 
        ref="courseFormRef"
        :model="courseForm"
        :rules="rules"
        label-width="100px"
        class="course-form">
        
        <!-- 课程名称 -->
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="courseForm.courseName" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        
        <!-- 课程分类 -->
        <el-form-item label="课程分类" prop="courseClassify">
          <el-select v-model="courseForm.courseClassify" placeholder="请选择课程分类">
            <el-option
              v-for="item in classifyOptions"
              :key="item.classifyId"
              :label="item.classifyName"
              :value="item.classifyName"
            />
          </el-select>
        </el-form-item>
        
        <!-- 课程封面 -->
        <el-form-item label="课程封面" prop="courseCover">
          <el-upload
            class="cover-uploader"
            :http-request="handleCustomUpload"
            :show-file-list="false">
            <img v-if="courseForm.courseCover" :src="courseForm.courseCover" class="cover-image">
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：800x450px，支持jpg、png格式</div>
        </el-form-item>
        
        <!-- 课程描述 -->
        <el-form-item label="课程描述" prop="courseDescription">
          <el-input
            v-model="courseForm.courseDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入课程描述">
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">创建课程</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { addCourse, getAllCourseClassify } from '@/api/course'
import { uploadFile } from '@/api/common'
import { useRouter } from 'vue-router'

// 表单数据
const courseForm = reactive({
  courseName: '',
  courseDescription: '',
  courseClassify: '',
  courseCover: ''
})

// 表单验证规则
const rules = {
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  courseClassify: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ],
  courseCover: [
    { required: true, message: '请上传课程封面', trigger: 'change' }
  ],
  courseDescription: [
    { required: true, message: '请输入课程描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 表单引用
const courseFormRef = ref(null)

// 分类选项
const classifyOptions = ref([])

// 处理封面图片上传成功（el-upload自定义上传）
const handleCustomUpload = async (option) => {
  try {
    const res = await uploadFile(option.file)
    if (res.code === 200) {
      courseForm.courseCover = res.data
      option.onSuccess(res, option.file)
    } else {
      option.onError(res.message || '上传失败')
    }
  } catch (err) {
    option.onError(err)
  }
}

// 提交表单
const submitForm = async () => {
  if (!courseFormRef.value) return
  // 先进行表单校验
  await courseFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        const res = await addCourse(courseForm)
        if (res.code === 0 || res.code === 200) {
          ElMessage.success('课程创建成功')
          router.push('/teacher/courses')
        } else {
          ElMessage.error(res.message || '课程创建失败')
        }
      } catch (error) {
        console.error('创建课程异常:', error)
        ElMessage.error(error.message || '课程创建失败，请稍后重试')
      }
    } else {
      ElMessage.error('请检查表单填写是否正确')
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!courseFormRef.value) return
  courseFormRef.value.resetFields()
}

// 获取所有课程分类
onMounted(async () => {
  const res = await getAllCourseClassify()
  if (res.code === 0 || res.code === 200) {
    classifyOptions.value = res.data.records || []
  }
})
</script>

<style scoped>
.create-course-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.course-form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.course-form {
  margin-top: 20px;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 169px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-uploader:hover {
  border-color: #409EFF;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 169px;
  text-align: center;
  line-height: 169px;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

:deep(.el-form-item__content) {
  line-height: normal;
}
</style> 